﻿using Microsoft.Phone.Tasks;
using Q42.WinRT.Data;
using SpaceNeedle.SDK.Windows.Platform.Commands;
using SpaceNeedle.SDK.Windows.Platform.Data;
using SpaceNeedle.SDK.WindowsPhone;
using SpaceNeedle.x6473.WindowsPhone.Common;
using SpaceNeedle.x6473.WindowsPhone.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;

namespace SpaceNeedle.x6473.WindowsPhone.ViewModels
{
    public class AlertsViewModel : GlobalViewModel
    {
        public AlertsViewModel() : base()
        {
            this.ClearAlertsCommand = new RelayCommand(ClearAlerts);
        }

        public AppContent.AlertsInfo StaticContent
        {
            get { return this.Get<AppContent.AlertsInfo>(); }
            set { this.Set(value); }
        }

        public string PageTitle
        {
            get { return this.Get<string>(); }
            set { this.Set(value); }
        }

        public ObservableCollection<Alert> Alerts
        {
            get { return this.Get<ObservableCollection<Alert>>(); }
            set { this.Set(value); }
        }
        
        protected async override void Load()
        {
            this.IsInProgress = true;

            await base.LoadAsync();

            this.StaticContent = this.AppContent.Alerts;

            if (!string.IsNullOrEmpty(AppViewModel.Instance.Properties.SelectedAlertId))
            {
                await AppViewModel.Instance.Cache.Delete(CacheKeys.Alerts);
            }

            this.Alerts = await AppViewModel.Instance.LoadAlerts();

            Tracking.SendView(ViewsNames.Alerts);

            this.IsInProgress = false;
        }

        public ICommand ClearAlertsCommand { get; set; }

        private async void ClearAlerts(object param)
        {
            this.IsInProgress = true;

            try
            {
                await AppViewModel.Instance.ClearAlerts();
                this.Alerts.Clear();
            }
            catch 
            {
                AppServices.Current.DialogService.Show("Não foi possível limpar a lista de alertas. Por favor tente novamente mais tarde.");
            }

            this.IsInProgress = false;
        }
    }
}
